"use strict";
// import ContentControlXml from './ContentControl'
import MyXml from './MyXml';
// import { PdCommonUtils } from '@plantdata/sdk';
import OfficeUtils from './OfficeUtils';

// 版本判断
export function isSupportWordApi(version = 1.1) {
  console.info("支持1.1吗？", Office.context.requirements.isSetSupported('WordApi', version))
  if (!Office.context.requirements.isSetSupported('WordApi', version)) {
    return false
  } else {
    return true
  }
}

// 插入图片
export function insertImage(base64) {
  if (isSupportWordApi()) {
    return Word.run(function (context) {
      const blankParagraph = context.document.getSelection().insertParagraph("", "After");
      blankParagraph.load()
      blankParagraph.insertInlinePictureFromBase64(base64.split(',')[1], Word.InsertLocation.end)
      return context.sync();
    }).catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  }
  OfficeUtils.insertImage(base64)
}

// 插入html
export function insertHtmlAfterParagraph(content) {
  if (isSupportWordApi()) {
    Word.run(function (context) {
      // const blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", "After");
      const blankParagraph = context.document.getSelection().insertParagraph("", "After");
      blankParagraph.load()
      blankParagraph.insertHtml(content, Word.InsertLocation.end)
      return context.sync().then(context.sync)
    }).catch(function (error) {
      console.log('Error:' + error);
    });
  } else {
    OfficeUtils.insertHtmlAfterParagraph(content)
  }
}

// 用ooxml替换word文档
export function replaceDocumentWithOoxml(content) {
  if (isSupportWordApi()) {
    Word.run(context => {
      var body = context.document.body
      body.insertOoxml(content, Word.InsertLocation.replace);
      return context.sync().then(function () {
        console.log('Paragraph added at the end of the document body.');
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo))
        }
      });
  } else {
    OfficeUtils.insertOoxmlAfterParagraph(content)
  }
}

export function insertTextAfterParagraph(content = "") {
  Word.run(function (context) {
    const blankParagraph = context.document.getSelection().insertParagraph("", "After");
    blankParagraph.load();
    return context.sync().then(function () {
      blankParagraph.insertText(content,
        Word.InsertLocation.end);
    }).then(context.sync);
  });
}

export function insertParagraph() {
  Word.run(function (context) {
    const docBody = context.document.body;
    docBody.insertParagraph(
      "Office has several versions, including Office 2016, Office 365 Click-to-Run, and Office Online.",
      "Start"
    );
    return context.sync();
  }).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

// 插入表格
export function insertTable(rows, columns, location, data) {
  console.log('测试：', rows, columns, location, data)
  if (isSupportWordApi()) { // word2016
    Word.run(function (context) {
      const secondParagraph = context.document.getSelection()
      secondParagraph.insertTable(rows, columns, location, data);
      return context.sync();
    }).catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  } else {  // word2013
    console.log('进入2013', [data[0]], [data.slice(1)])
    var tableData = new Office.TableData();
    tableData.headers = [data[0]];
    tableData.rows = data.slice(1);
    OfficeUtils.insertTable(tableData)
  }

}

// Function that writes to a div with id='message' on the page.
function write(message) {
  console.log(message)
  document.getElementById("message").innerText = message;
}
function onError(message) {
  document.getElementById("message").innerText = message;
}

// Check for existence of named content control by trying to bind to it.
// If binding fails because the control doesn't exist, add named content control at the selection and then bind to it.
export function addAndBindControl() {

  Office.context.document.bindings.addFromNamedItemAsync("MyContentControlTitle", Office.BindingType.Text, { id: 'myBinding' },
    function (result) {

      if (result.status === Office.AsyncResultStatus.Failed) {

        // Error 3006 message: "The named item does not exist."
        // If the named item doesn't exist, then add and bind to it.
        if (result.error.code === 3006) {
          var myOOXMLRequest = new XMLHttpRequest();
          var myXML;
          myOOXMLRequest.open('GET', '../../Snippets_BindAndPopulate/ContentControl.xml', false);
          myOOXMLRequest.send();

          if (myOOXMLRequest.status === 200) {
            myXML = myOOXMLRequest.responseText;
          }
          myXML = MyXml
          Office.context.document.setSelectedDataAsync(myXML, { coercionType: 'ooxml' }, function () {
            Office.context.document.bindings.addFromNamedItemAsync("MyContentControlTitle", Office.BindingType.Text, { id: 'myBinding' });
          });
        }
        else write(result.error.name + " " + result.error.code + result.error.message);
      }
    });
}


// 注释 添加 事件
// The following example adds an event handler for the SelectionChanged event to the binding with an id of myTable.
// When the user changes the selection, the handler displays the coordinates of the first cell in the selection,
// and the number of row and columns selected.
function addSelectionHandler() {
  Office.context.document.bindings.getByIdAsync("myTable", function (result) {
    result.value.addHandlerAsync("bindingSelectionChanged", myHandler);
  });
}

// Display selection start coordinates and row/column count.
function myHandler(bArgs) {
  write("Selection start row/col: " + bArgs.startRow + "," + bArgs.startColumn);
  write("Selection row count: " + bArgs.rowCount);
  write("Selection col count: " + bArgs.columnCount);
}

export const getSelectedDataAsync = async () => { // todo
  console.log("进入方法: ");
  Office.context.document.getSelectedDataAsync(
    Office.CoercionType.Text,
    function (result) {
      write("Selected data: " + result.value);
      console.log("进入: ", result);
    }
  );
};

// Get the GUID of the selected resource and display it in the add-in.
export function getResourceGuid() {
  Office.context.document.getSelectedResourceAsync( // 方法不存在 ？？？
    function (result) {
      console.log('getResourceGuid', result)
      if (result.status === Office.AsyncResultStatus.Failed) {
        onError(result.error);
      }
      else {
        write(result.value);
      }
    }
  );
}
// Display the user's current selection.
export function showSelection() {
  Office.context.document.getSelectedDataAsync(
    Office.CoercionType.Html,                        // coercionType
    {
      valueFormat: "formatted",   // valueFormat
      filterType: Office.FilterType.All //  |'all'| visible
    },            // filterType
    function (result) {            // callback
      var dataValue;
      dataValue = result.value;
      console.info('Selected data is: ' + dataValue);
    });
}


// export const addHandlerAsync = (EventType: Office.EventType, myHandler: Function) => {
//   console.log("监听 进入了: "); write('进入了');
//   Office.context.document.addHandlerAsync(EventType, myHandler, function (result) { }
//   );
// }
// export const selectChange = (myHandler) => {
//   addHandlerAsync(Office.EventType.DocumentSelectionChanged, myHandler)
// }

// Event handler function.
// function myHandler(eventArgs) {
//   console.log("监听: ");
//   write('Document Selection Changed');
// }



// 在选定内容插入文档内容
export function writeMyOOXMLContent() {
  var myOOXMLRequest = new XMLHttpRequest();
  var myXML;
  myOOXMLRequest.open('GET', 'yourXMLfilename', false);
  myOOXMLRequest.send();
  if (myOOXMLRequest.status === 200) {
    myXML = myOOXMLRequest.responseText;
  }
  myXML = MyXml
  Office.context.document.setSelectedDataAsync(myXML, { coercionType: 'ooxml' });
}

export function createContentControl() {
  Word.run(function (context) {
    const serviceNameRange = context.document.getSelection();
    // const serviceNameContentControl = serviceNameRange.insertContentControl();
    // serviceNameContentControl.title = "名字";
    // serviceNameContentControl.tag = "serviceName";
    // serviceNameContentControl.appearance = "Text";
    // serviceNameContentControl.color = "blue";

    var myContentControl = serviceNameRange.insertContentControl();
    myContentControl.tag = "serviceName";
    myContentControl.title = "title输入";
    myContentControl.appearance = "Tags"; // Word.ContentControlAppearance "BoundingBox" | "Tags" | "Hidden";
    myContentControl.style = "Normal";
    myContentControl.color = "blue";
    myContentControl.insertText("One Microsoft Way, Redmond, WA 98052", 'replace');
    myContentControl.cannotEdit = true;

    return context.sync();
  }).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

export function replaceContentInControl() {
  Word.run(function (context) {
    const serviceNameContentControl = context.document.contentControls
      .getByTag("serviceName")
      .getFirst();
    serviceNameContentControl.insertText(
      "替换成功了",
      "Replace"
    );

    return context.sync();
  }).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

export function showXMLPartsInNamespace() {
  Office.context.document.customXmlParts.getByNamespaceAsync(
    "kg",
    function (eventArgs) {
      console.log('kg run namespace', JSON.stringify(eventArgs))
      Office.context.document.customXmlParts.getByIdAsync(
        eventArgs.value[0].id, function (result) {
          console.log('kg run id', JSON.stringify(result))
          var xmlPart = result.value;
          xmlPart.getXmlAsync({}, function (ele) {
            console.log('kg run id', JSON.stringify(ele))
            write(ele.value);
          });
        });
    });
}

export function addXMLPart(id) {
  Office.context.document.customXmlParts.addAsync(
    `<kg xmlns="kg"><page number="1">${id}</page></kg>`,
    function (result) {
      console.log('addXMLPart', result)
    });
}
